/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.iss.basket.service;

import com.iss.basket.ajaxModels.ProductList;
import com.iss.basket.bizLogic.ProductService;
import com.iss.basket.models.Inventory;
import com.iss.basket.service.sse.InventoryHandler;
import javax.ejb.EJB;
import javax.inject.Inject;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import org.glassfish.sse.api.ServerSentEventContext;
import org.glassfish.sse.api.ServerSentEventData;
import org.glassfish.sse.api.ServerSentEventHandlerContext;

/**
 *
 * @author yc
 */
@Path("/Products")
public class ProductWebSvc {
    @EJB private ProductService service;
    
    @Inject @ServerSentEventContext("/inventory")
    ServerSentEventHandlerContext<InventoryHandler> context;
    
    
    @POST
    @Path("/get")
    @Produces("application/json")
    @Consumes("application/json")
    public ProductList getProducts(JsonObject request)
    {
        int currentPage = Integer.parseInt(request.get("currentPage").toString());
        int resultsPerPage = Integer.parseInt(request.get("resultsPerPage").toString());
        
        return service.getProducts(currentPage, resultsPerPage);
        
    }
    
    @POST
    @Path("/details")
    @Produces("application/json")
    @Consumes("application/json")
    public Inventory getProductDetails(JsonObject request)
    {
        if(request.get("productId")!=null)
        {
            int productId = Integer.parseInt(request.get("productId").toString());
            return service.getProductDetail(productId);
        }
        else
        {
            return new Inventory();
        }
    }
    
    
    @POST
    @Path("/pushInventory")
    public void pushInventoryUpdate()
    {
        JsonObjectBuilder response = Json.createObjectBuilder();
        response.add("productId", "1").add("qty", "1");
        ServerSentEventData data = new ServerSentEventData();
        data.event("1"); //set event
        data.data(response.build().toString());
        
        //send to each connection
        for(InventoryHandler h: context.getHandlers())
        {
            h.sendInventoryUpdate(data);    
        }
        
        //TODO: Some output?
    }
}
